package service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;



import pojo.*;





import base.BaseService;

public class CartService extends BaseService {
	public class CartRowMapper implements RowMapper<cart> {
		
	  	   public cart mapRow(ResultSet rs, int rownum) throws SQLException {
	  
		cart inf = new cart();
		inf.setId(rs.getInt("id"));
		inf.setUserId(rs.getInt("userId"));
		inf.setDishesId(rs.getInt("dishesId"));
		inf.setDishesNum(rs.getInt("dishesNum"));
		inf.setPartPrice(rs.getFloat("partPrice"));
		return inf;
		
}
	}
	
	public cart getCart(int id){
		String sql="select * from cart where id="+id;
		return jdbcTemplate.queryForObject(sql,new CartRowMapper());
		
	}
	public int getALL(int id){
		String sql = "SELECT count(*) FROM cart where userId="+id;	
		int count1 = this.jdbcTemplate.queryForInt(sql);	
		return count1;
		
	}
	public List<dishes> getDishes(int pageno,int pagesize,int userId){
		@SuppressWarnings("unused")
		class RowMapper implements org.springframework.jdbc.core.RowMapper<dishes> {
			 public dishes mapRow(ResultSet rs, int rownum) throws SQLException {
				 dishes dt = new dishes();
				    dt.setId(rs.getInt("id"));
				    dt.setName(rs.getString("name"));
					dt.setType(rs.getInt("type")); 
					dt.setPicture(rs.getString("picture"));
					dt.setSale(rs.getInt("sale"));
					dt.setPrice(rs.getFloat("price"));				
					return dt;
							}
					}
		String sql = "SELECT cart.id as id,dishes.id as s,dishes.name,price,picture,type,sale,price from dishes join cart on cart.dishesId=dishes.id where userId="+userId+" limit "+(pageno-1)*pagesize+","+pagesize;
		return jdbcTemplate.query(sql,new RowMapper());
}
	public int order(int userId,int dishesId,int dishesNum,float partPrice){
		String sql ="insert into cart(userId,dishesId,dishesNum,partPrice) values(?,?,?,?)";
		return jdbcTemplate.update(sql,userId,dishesId,dishesNum,partPrice);
	}
		public float gettotalprice(int userId){
			String sql="select sum(cart.partPrice) from cart where userid="+userId;
			return this.jdbcTemplate.queryForInt(sql);
			
		}
		

		public int deleteCart(int id){
			String sql = "delete from cart where id="+id;	
			 return this.jdbcTemplate.update(sql);	
			
			
		}
		public int count(int userId,int dishesId){
			String sql="select count(*) from cart where userId="+userId+" and dishesId="+dishesId;
			return this.jdbcTemplate.queryForInt(sql);
		}
	}
		
		
		
		
		
		
		
		
	

